package com.ruoyi.zsyh.controller.applet.wechat.util;

import com.ruoyi.zsyh.controller.applet.wechat.menu.Menu;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MenuUtil {
	private static Logger log = LoggerFactory.getLogger(MenuUtil.class);

	// 菜单创建（POST） 限100（次/天）
	public final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	// 菜单查询（GET)
	public final static String menu_get_url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	// 菜单删除（GET)
	public final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";

	/**
	 * 创建菜单
	 * 
	 * @param menu
	 *            菜单实例
	 * @param accessToken
	 *            有效的access_token
	 * @return true表示成功，false表示失败
	 */
	public static boolean createMenu(Menu menu, String accessToken) {
		boolean result = false;

		// 拼装创建菜单的url
		String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
		System.err.println(url);
		// 将菜单对象转换成json字符串
		String jsonMenu = JSONObject.fromObject(menu).toString();
		// 调用接口创建菜单
		JSONObject jsonObject = WeiXinUtil.httpRequest(url, "POST", jsonMenu);
		if (null != jsonObject) {
			System.err.println(jsonObject.getInt("errcode"));
			if (0 == jsonObject.getInt("errcode")) {
				result = true;
			} else {
				result = false;
				log.error("创建菜单失败 errcode:{} errmsg:{}",
						jsonObject.getInt("errcode"),
						jsonObject.getString("errmsg"));

			}
		}
		return result;
	}

	/**
	 * 查询菜单
	 * 
	 * @param accessToken
	 * @param accessToken
	 * @return
	 */
	public static JSONObject getMenu(String accessToken) {
		//String result = null;

		// 拼装创建菜单的url
		String requestUrl = menu_get_url.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = WeiXinUtil.httpRequest(requestUrl, "GET", null);

		/*if (null != jsonObject) {
			result = jsonObject.toString();
		}*/
		return jsonObject;
	}

	/**
	 * 删除菜单
	 * 
	 * @param menu
	 * @param accessToken
	 * @return true表示成功，false表示失败
	 */
	public static boolean deleteMenu(Menu menu, String accessToken) {
		boolean result = false;
		// 拼装创建菜单的url
		String requestUrl = menu_delete_url
				.replace("ACCESS_TOKEN", accessToken);
		// 调用接口创建菜单
		JSONObject jsonObject = WeiXinUtil.httpRequest(requestUrl, "GET", null);

		if (null != jsonObject) {
			int errorCode = jsonObject.getInt("errcode");
			String errorMsg = jsonObject.getString("errmsg");
			if (0 == errorCode) {
				result = true;
			} else {
				result = false;
				log.error("创建菜单失败 errcode:{} errmsg:{}", errorCode, errorMsg);

			}
		}
		return result;
	}
}
